package tech.shupi.babytaptv

import android.media.AudioManager
import android.media.MediaPlayer
import android.util.Base64
import com.facebook.react.bridge.*
import java.io.ByteArrayInputStream
import java.io.IOException

class AudioModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {

    override fun getName(): String {
        return "AudioModule"
    }

    private var mediaPlayer: MediaPlayer? = null
    private var audioManager: AudioManager = reactContext.getSystemService(android.content.Context.AUDIO_SERVICE) as AudioManager

    @ReactMethod
    fun playAudio(audioData: String, promise: Promise) {
        try {
            // 停止当前播放
            stopAudioInternal()
            
            // 请求音频焦点
            val result = audioManager.requestAudioFocus(
                null,
                AudioManager.STREAM_MUSIC,
                AudioManager.AUDIOFOCUS_GAIN
            )
            
            if (result != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                promise.reject("AUDIO_FOCUS_ERROR", "无法获取音频焦点")
                return
            }
            
            // 判断是否是本地文件路径
            if (audioData.startsWith("audio/") || audioData.startsWith("file://")) {
                // 本地文件路径，直接使用
                val audioFile = java.io.File(reactApplicationContext.filesDir, audioData)
                
                if (audioFile.exists()) {
                    // 创建 MediaPlayer 直接播放本地文件
                    mediaPlayer = MediaPlayer().apply {
                        setDataSource(audioFile.absolutePath)
                        prepare()
                        start()
                    }
                    promise.resolve(true)
                } else {
                    promise.reject("AUDIO_FILE_NOT_FOUND", "本地音频文件不存在: $audioData")
                }
            } else {
                // 解析 base64 数据
                val base64Data = if (audioData.startsWith("data:audio/mpeg;base64,")) {
                    audioData.substring("data:audio/mpeg;base64,".length)
                } else {
                    audioData
                }
                
                val audioBytes = Base64.decode(base64Data, Base64.DEFAULT)
                
                // 创建临时文件来播放音频
                val tempFile = java.io.File.createTempFile("audio", ".mp3", reactApplicationContext.cacheDir)
                tempFile.writeBytes(audioBytes)
                
                // 创建 MediaPlayer
                mediaPlayer = MediaPlayer().apply {
                    setDataSource(tempFile.absolutePath)
                    prepare()
                    start()
                }
                
                promise.resolve(true)
            }
        } catch (e: Exception) {
            promise.reject("AUDIO_PLAY_ERROR", e.message, e)
        }
    }

    @ReactMethod
    fun stopAudio(promise: Promise) {
        try {
            stopAudioInternal()
            promise.resolve(true)
        } catch (e: Exception) {
            promise.reject("AUDIO_STOP_ERROR", e.message, e)
        }
    }

    @ReactMethod
    fun isPlaying(promise: Promise) {
        try {
            val playing = mediaPlayer?.isPlaying ?: false
            promise.resolve(playing)
        } catch (e: Exception) {
            promise.reject("AUDIO_STATUS_ERROR", e.message, e)
        }
    }

    private fun stopAudioInternal() {
        mediaPlayer?.let { player ->
            if (player.isPlaying) {
                player.stop()
            }
            player.release()
        }
        mediaPlayer = null
        
        // 释放音频焦点
        audioManager.abandonAudioFocus(null)
    }

    override fun onCatalystInstanceDestroy() {
        super.onCatalystInstanceDestroy()
        stopAudioInternal()
    }
} 